package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        //去完成对simpleexcutor里的query方法调用
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        List<Object> query = simpleExcutor.query(configuration, mappedStatementMap.get(statementId), params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException(String.format("the size is %s,not one!", objects.size()));
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理来为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            /**
             *
             * @param proxy 当前参数的引用
             * @param method 当前要执行的方法
             * @param args 传递过来的参数
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //根据不同情况，来调用selectList还是selectOne
                //准备参数1.statementId,sql的唯一id：namespace.id=全限定名.方法名。2、params

                //方法名findAll
                String methodName = method.getName();
                //全限定名
                String name = method.getDeclaringClass().getName();
                String statementId = name + "." + methodName;
                //获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                String sqlType = configuration.getMappedStatementMap().get(statementId).getSqlType();
                switch (sqlType) {
                    case "//select":
                        //判断是否进行了反省类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        }
                        return selectOne(statementId, args);
                    case "//update":
                        return update(statementId,args);
                    case "//delete":
                        return delete(statementId,args);
                    case "//insert":
                        return insert(statementId,args);
                    default:
                        throw new RuntimeException(String.format("can not find this type:%s!", sqlType));
                }
            }
        });

        return (T) proxyInstance;
    }

    @Override
    public <T> int update(String statementId, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        return simpleExcutor.update(configuration, mappedStatementMap.get(statementId), params);
    }

    @Override
    public <T> int insert(String statementId, Object... params) throws ClassNotFoundException, SQLException, NoSuchFieldException, IllegalAccessException {
        return update(statementId,params);
    }

    @Override
    public <T> int delete(String statementId, Object... params) throws ClassNotFoundException, SQLException, NoSuchFieldException, IllegalAccessException {
        return update(statementId,params);
    }

}
